#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include "cvMatConversionQImage.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    p_mask_detection = new(class mask_detection);
    p_mask_detection->init();

    p_cap_thread = new capture_thread;

    connect(p_cap_thread, SIGNAL(image_update(QImage)), this, SLOT(update_img(QImage)));

    ui->setupUi(this);

    p_cap_thread->start();
}

MainWindow::~MainWindow()
{
    p_cap_thread->quit();
    delete p_mask_detection;
    delete p_cap_thread;
    delete ui;
}

void MainWindow::set_qpixmap(QPixmap &qmap)
{
    this->ui->label->setPixmap(qmap);
    this->ui->label->show();
}

void MainWindow::update_img(QImage src_img)
{
//   qDebug() << "update_img!" << endl;
    ui->label->setPixmap(QPixmap::fromImage(src_img));

    // get temperature
    if(get_temperature(&temp_object, &temp_ambient) < 0){
        return;
    }
    ui->label_2->setText(QString("环境温度:%1").arg(temp_ambient));
    ui->label_3->setText(QString("检测温度:%1").arg(temp_object));
    if(temp_object - temp_ambient > 5){ // detection
//        p_cap_thread->quit();
        ui->label_4->setPixmap(QPixmap::fromImage(detection_mask(src_img)));
        ui->label_5->setText(QString("检测温度:%1").arg(temp_object));
//        p_cap_thread->sleep(5);
//        p_cap_thread->start();
    }
}

QImage MainWindow::detection_mask(QImage src_img)
{
    QImage result;
    cv::Mat mat;
    mat = cvMatConversionQImage::QImage2Mat(src_img);
    cv::Mat image(src_img.height(), src_img.width(), CV_8UC3, src_img.bits());
    cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
    mat = p_mask_detection->detection(image);
    result = cvMatConversionQImage::Mat2QImage(mat);
    return result;
}
